package com.welab.springcloud.demo.order.service;

import com.welab.springcloud.demo.api.GoodsApi;
import com.welab.springcloud.demo.api.UserApi;
import com.welab.springcloud.demo.common.exception.BizException;
import com.welab.springcloud.demo.dto.Goods;
import com.welab.springcloud.demo.dto.Order;
import com.welab.springcloud.demo.dto.ResponseResult;
import com.welab.springcloud.demo.dto.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.welab.springcloud.demo.dto.ResponseResult.FAIL_CODE;

@Service
public class OrderService {

    @Resource
    UserApi userApi;

    @Resource
    GoodsApi goodsApi;

    public List<Order> getUserOrder(Integer userId) {

        ResponseResult<User> userResult  = userApi.getUser(userId);
        if (userResult == null || !userResult.isSuccess() || userResult.getData() == null) {
            throw new BizException(FAIL_CODE, "用户不存在");
        }

        ResponseResult<List<Goods>> goodsResult = goodsApi.userGoods(userId);
        if (goodsResult == null || !goodsResult.isSuccess() || goodsResult.getData() == null) {
            throw new BizException(FAIL_CODE, "用户没购买商品");
        }

        Order order = Order.builder().build();
        order.setUser(userResult.getData());
        order.setGoodsList(goodsResult.getData());
        BigDecimal totalAmount = BigDecimal.ZERO;
        goodsResult.getData().forEach(goods -> totalAmount.add(new BigDecimal(goods.getNumber()*goods.getNumber())));
        order.setTotalAmount(totalAmount.doubleValue());

        List<Order> orderList = new ArrayList<>();
        orderList.add(order);

        return orderList;
    }

    public void orderSave(Integer userId) {

    }

}
